package com.lijing.knapsackProblem;

import java.util.Arrays;

/**
 * @Description 0-1 KnapsackProblem
 * @title: KnapsackProblem
 * @Author LiJing
 * @Date: 2021/4/14:43 下午
 * @Version 1.0
 */
public class KnapsackProblem {
    public static void main(String[] args) {
        //商品容量
        int[] weight = {1, 4, 3,5,7,10,11};
        //商品价值
        int[] value = {1500, 3000, 2000,4000,3000,2000,1200};
        //背包容量
        int m = 25;
        int n = value.length;

        //最优配置表，横坐标为商品编号，纵坐标为背包容量
        int[][] v = new int[n+1][m+1];
        int[][] path = new int[n+1][m+1];

        /*
         * @Date: 2021/4/1 4:53 下午
         * Step 1: 首先初始化，将v第一行和第一列全部置为0
         * 在本程序中，可以不初始化，因为默认也为0
         */
        Arrays.fill(v[0], 0);
        for (int i = 0; i < v.length; i++) {
            v[i][0] = 0;
        }
        /*
         * @Date: 2021/4/1 4:59 下午
         * Step 2: 根据状态转换公式修改
         */
        for (int i = 1; i < v.length; i++) {
            for (int j = 1; j < v[i].length; j++) {
                if (j < weight[i - 1]){
                    v[i][j] = v[i-1][j];
                }else {
                    //v[i][j] = Math.max(v[i - 1][j],value[i-1]+v[i-1][j-weight[i-1]]);
                    //为记录商品存放情况，需使用if-else
                    if (v[i-1][j] < value[i-1]+v[i-1][j-weight[i-1]]){
                        v[i][j] = value[i-1]+v[i-1][j-weight[i-1]];
                        path[i][j] = 1;
                    }else {
                        v[i][j] = v[i-1][j];
                    }
                }
            }
        }
        show(v);

        int i = path.length - 1;
        int j = path[0].length - 1;
        while (i > 0 && j > 0){
            if (path[i][j] == 1){
                System.out.printf("第%d个商品放入到背包\n", i);
                j -= weight[i-1];
            }
            i--;
        }


    }

    /**
     * print arr
     * @param arr arr
     */
    public static void show(int[][] arr){
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.print(anInt + " ");
            }
            System.out.println();
        }
    }

}
